/*
 * ClientWorker.cpp
 *
 *  Created on: May 24, 2011
 *      Author: madboyka
 */

#include "ClientWorker.h"
#include "ClientProtocol.h"
#include <QThread>
#include "Logger.h"

ClientWorker::ClientWorker(Server* server, ClientProtocol* protocol)
{
	this->server = server;
	this->protocol = protocol;
}

ClientWorker::~ClientWorker()
{
	Logger::log("Closing client socket!");
	protocol->close();
	delete protocol;
}

void ClientWorker::run()
{
	running = true;
	char *csd = protocol->receiveConnect();
	robotName = QString(csd);
	robot = server->world->addRobot(csd);
	Logger::debug("Client connected with robot: %s !", csd);
	if (robot == NULL)
	{
		Logger::error("Unknown robot type: %s !", csd);
		return;
	}
	robot->setPosition(1, 5, 6);
	server->world->activateRobot(robot);
	while (running)
	{
		int dir;
		try
		{
			dir = protocol->receive();
			Logger::log("Got Command: %d ", dir);
		} catch (NetworkException ex)
		{
			running = false;
			server->killClient(this);
		}
		if (robotName == QString("Acrobat")) {
		float bla[1];
		switch (dir)
		{
		case UP:
			break;
		case DOWN:
			break;
		case LEFT:
				bla[0] = -40;
				robot->command(0, 1, bla);
			break;
		case RIGHT:
				bla[0] = 40;
				robot->command(0, 1, bla);
			break;
		}
		} else {
			robot->command(dir,protocol->getParameterCount(),protocol->getParameters());
		}
	}
}
